package day2_linkedlist.leetcode;

/**
 * @Author: yuisama
 * @Date: 2021/9/1 16:43
 * @Description:删除链表中倒数第n个节点
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 */
public class Num19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode(-1,head);
        ListNode p = dummyHead,q =dummyHead;
        // 保持p与q相对位置为n，则当q节点为null时，p节点为待删除节点的前驱
        for (int i = 0; i < n + 1; i++) {
            q = q.next;
        }
        while (q != null) {
            p = p.next;
            q = q.next;
        }
        // 此时p节点为待删除节点的前驱
        p.next = p.next.next;
        return dummyHead.next;
    }
}
